package cn.lanqiao.springbootproject.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

@Service
public class ProductService {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * return 1:已经参加过 2:库存不足 3:秒杀成功
     * <p>
     * 库存：killId:10001 = 1000
     * 订单：killId:10001:userSet = [101,102,103,104]
     */

    @Transactional
    public int killProduct(int userId, int killId) {
        //1、判断用户是否参加过
        boolean isExist = redisTemplate.opsForSet().isMember("killId:" + killId + ":userSet", userId);
        if (isExist) {
            return 1;
        }
        //2、判断库存
        int count = (Integer) redisTemplate.opsForValue().get("killId:" + killId);
        if (count <= 0) {
            return 2;
        }
        //3、生成订单
        redisTemplate.opsForSet().add("killId:" + killId + ":userSet", userId);
        //4、更新库存
        redisTemplate.opsForValue().decrement("killId:" + killId, 1);
        return 3;
    }

    public Long killProductLua(int userId, int killId) {
        final String KILL_LUA_SCRIPT = "local isExist = redis.call('sismember',KEYS[1],ARGV[1]) if isExist == 1 then return 1 end "
                + "local count = redis.call('get',KEYS[2]) if count == '0' then return 2 end "
                + "redis.call('sadd',KEYS[1],ARGV[1]) "
                + "redis.call('decr',KEYS[2]) return 3 ";
        return (Long) redisTemplate.execute(RedisScript.of(KILL_LUA_SCRIPT, Long.class), Arrays.asList("killId:" + killId + ":userSet","killId:" + killId), userId);
    }
}
